package com.cjkj.equipment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.iot.model.v20180120.PubRequest;
import com.aliyuncs.iot.model.v20180120.PubResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.cjkj.common.core.constant.*;
import com.cjkj.common.core.domain.R;
import com.cjkj.common.core.domain.runset.RunSetParam;
import com.cjkj.common.core.exception.ServiceException;
import com.cjkj.common.core.utils.DateUtils;
import com.cjkj.common.core.utils.DecimalUtils;
import com.cjkj.common.core.utils.StringUtils;
import com.cjkj.common.core.utils.bean.BeanUtils;
import com.cjkj.equipment.config.AMQPConfig;
import com.cjkj.equipment.domain.*;
import com.cjkj.equipment.domain.dto.EquipmentStatusDto;
import com.cjkj.equipment.domain.dto.TJ03DataDto;
import com.cjkj.equipment.mapper.*;
import com.cjkj.equipment.service.ITWarnRecordsService;
import com.cjkj.equipment.service.TJ03DataService;
import com.cjkj.system.api.RemoteHospitalEquipmentService;
import com.cjkj.system.api.domain.*;
import com.cjkj.system.api.domain.request.RecordsReq;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.jms.Message;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class TJ03DataServiceImpl implements TJ03DataService {

    /** 心电数据帧头 */
    private static final String ECG_HEADER = "FFE0";
    /** 心率数据帧头 */
    private static final String HR_HEADER = "FFF0";
    /** 脱落数据帧头 */
    private static final String TALL_OF_HEADER = "FFAA";
    /**  包结尾 */
    private static final String DATA_END = "DD";
    /** 时间数据占位大小 */
    private static final int DATE_TIME_SIZE = 18;
    /** 日志打印 */
    private static final Logger deviceLog = LoggerFactory.getLogger("device-tj03-log");
    @Resource
    AMQPConfig amqp;
    @Resource
    private TEquipmentInfoMapper equipmentInfoMapper;
    @Resource
    private RemoteHospitalEquipmentService remoteHospitalEquipmentService;
    @Resource
    private TWarnSettingMapper warnSettingMapper;
    @Resource
    private TJ03DataMapper j03DataMapper;
    @Resource
    private TJ03DataEcgMapper j03DataEcgMapper;
    @Resource
    private TJ03DataHrMapper j03DataHrMapper;
    @Resource
    private ITWarnRecordsService recordsService;

    @Override
    public void processMessage(Message message) {
        byte[] body;
        try {
            body = message.getBody(byte[].class);
        } catch (Exception e){
            deviceLog.error("processMessage occurs error ", e);
            throw new ServiceException("数据采集失败："+e);
        }
        String content = new String(body);
        deviceLog.info(content);
        TJ03DataDto dto = JSONObject.parseObject(content, TJ03DataDto.class);
        EquipmentStatusDto statusDto = JSONObject.parseObject(content, EquipmentStatusDto.class);

        if (dto.getItems() == null) {
            return ;
        }
        // 正在使用的设备才保存数据
        String equipmentNo = dto.getDeviceName();

        /* 查询是否系统的设备 */
        TEquipmentInfo equipmentInfo = equipmentInfoMapper.selectEquipment(EquipmentConstants.EQUIPMENT_TYPE_EB_TYPE, equipmentNo);
        if(equipmentInfo == null || EquipmentConstants.EQUIPMENT_ALLOCATION_FLAG_UNALLOTTED.equals(equipmentInfo.getDistributeFlag())) {
            return ;
        }
        /* 判断该设备是否在开单使用 */
        R<APIEquipmentUsageRecords> records = remoteHospitalEquipmentService.getRecordsByEquipment(equipmentNo, SecurityConstants.INNER);
        APIEquipmentUsageRecords useRecord = records.getData();
        if(HttpStatus.SUCCESS != records.getCode() || useRecord == null){
            return ;
        }

        // 添加监测记录
        TJ03Data record = getRecordFromDto(dto);
        int inserted = j03DataMapper.insertTJ03MonitorRecords(record);
        if(inserted < 1){
            deviceLog.error("添加监测记录失败：{}", record);
            return;
        }
        // 解析心电、心率，并保存至数据库
        int hr = saveECGData(record);
        record.setHr(hr);
        /* 保存使用期间的心电贴编号数据 */
        String ecgSeq = record.getEcgSeq();
        if(StringUtils.isNotBlank(ecgSeq)) {
            saveSensorSeq(useRecord, ecgSeq);
        }

        /* 报警判断 */
        judgeWarn(record, useRecord);
    }

    /**
     * 保存就诊患者使用的传感器编号数据
     * @param useRecord 使用记录
     * @param dataTempSeq 传感器编号
     */
    private void saveSensorSeq(APIEquipmentUsageRecords useRecord, String dataTempSeq){
        String sensorSeq = useRecord.getSensorSeq();
        String seqStr = "";
        if(StringUtils.isBlank(sensorSeq)) {
            // 如果该设备没有使用传感器编号数据
            seqStr = dataTempSeq;
        } else {
            if(! sensorSeq.contains(dataTempSeq)) {
                seqStr = sensorSeq + "," + dataTempSeq;
            }
        }

        // 保存数据
        APIEquipmentUsageRecords updateInfo = new APIEquipmentUsageRecords();
        updateInfo.setUseId(useRecord.getUseId());
        updateInfo.setSensorSeq(seqStr);
        remoteHospitalEquipmentService.updateEquipmentUsageRecordStatus(updateInfo, SecurityConstants.INNER);
    }

    /**
     * 保存心电、心率数据
     */
    private int saveECGData(TJ03Data record){
        // 解密心电数据
        String hex = "";
        String base64Str = record.getEcgData();
        if(StringUtils.isNotBlank(base64Str)) {
            hex = StringUtils.base64ToHex(base64Str);
            hex = hex.toUpperCase();
            hex = hex.substring(0, hex.lastIndexOf(DATA_END) + DATA_END.length());
        }
        // 打印信息到日志
        deviceLog.info("RecordId：{}，EquipmentNo：{}，DateTime：{}，EcgData：{}", record.getId(), record.getEquipmentNo(), DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, record.getCreateTime()), hex);

        if(StringUtils.isBlank(hex)) {
            return 0;
        }
        List<String> ecgData = new ArrayList<>();
        List<String> hrData = new ArrayList<>();
        List<String> tallOfData = new ArrayList<>();
        do {
            if(hex.length() < 22) {
                break ;
            }
            // 数据帧头
            String dataHead = hex.substring(DATE_TIME_SIZE, 22);
            String dataStr = "";
            if (ECG_HEADER.equals(dataHead)) {
                // 数据长度
                String dataNums = hex.substring(22, 24);
                int decimalNumber = DecimalUtils.getDecimalNumber(dataNums);
                dataStr = hex.substring(0, decimalNumber * 2 + 24 + DATA_END.length());
                ecgData.add(dataStr);
            }
            if (HR_HEADER.equals(dataHead)) {
                // 数据长度
                String dataNums = hex.substring(22, 24);
                int decimalNumber = DecimalUtils.getDecimalNumber(dataNums);
                dataStr = hex.substring(0, decimalNumber * 2 + 24 + DATA_END.length());
                hrData.add(dataStr);
            }
            if (TALL_OF_HEADER.equals(dataHead)) {
                dataStr = hex.substring(0, DATE_TIME_SIZE + dataHead.length() + DATA_END.length());
                tallOfData.add(dataStr);
            }

            hex = hex.substring((StringUtils.isNotBlank(dataStr) ? dataStr : dataHead).length());

        } while (!hex.isEmpty());

        // 添加心电数据
        for (String s : ecgData) {
            Date hexTime = DateUtils.getHexTime(s);
            String data = s.substring(24, s.lastIndexOf(DATA_END));

            List<Integer> ecgNumberList = new ArrayList<>();
            do {
                if (data.length() < 4) {
                    break;
                }
                String ecgHex = data.substring(0, 4);
                ecgNumberList.add(DecimalUtils.int16HexToDecimal(ecgHex));
                data = data.substring(4);
            } while (!data.isEmpty());
            String collect = ecgNumberList.stream().map(String::valueOf).collect(Collectors.joining(","));

            TJ03DataEcg ecgEntity = new TJ03DataEcg();
            ecgEntity.setRecordId(record.getId());
            ecgEntity.setEquipmentNo(record.getEquipmentNo());
            ecgEntity.setCreateTime(hexTime.getTime());
            ecgEntity.setEcgData(collect);
            j03DataEcgMapper.insertEquipmentTj03MonitorRecordsEcg(ecgEntity);
        }

        // 添加心率数据
        int hr = 0;
        for (String s : hrData) {
            Date hexTime = DateUtils.getHexTime(s);
            String data = s.substring(24, s.lastIndexOf(DATA_END));
            hr = DecimalUtils.hexToDecimal(data);

            TJ03DataHr hrEntity = new TJ03DataHr();
            hrEntity.setRecordId(record.getId());
            hrEntity.setEquipmentNo(record.getEquipmentNo());
            hrEntity.setCreateTime(hexTime.getTime());
            hrEntity.setHr(hr);
            j03DataHrMapper.insertEquipmentTj03MonitorRecordsHr(hrEntity);
            record.setHr(hr);
        }

        return hr;
    }

    private void judgeWarn(TJ03Data data, APIEquipmentUsageRecords record){
        if(data == null) {
            return ;
        }
        // 预警信息
        List<TWarnRecords> warnRecords = new ArrayList<>();

        // 查询预警设置
        List<TWarnSetting> warnSettings = warnSettingMapper.selectTWarnSettingList(new TWarnSetting());
        warnSettings.forEach( e -> {
            String warnType = e.getWarnType();
            // 心率预警
            if(WarnConstants.WARN_TYPE_HR.equals(warnType)){
                Integer heartRate = data.getHr();
                String content = "";
                if(null != heartRate && heartRate != 0 && heartRate < e.getLowerLimit()){
                    content = WarnConstants.WARN_CONTENT_HEART_LOW;
                }
                if(null != heartRate && heartRate != 0 && heartRate > e.getUpperLimit()){
                    content = WarnConstants.WARN_CONTENT_HEART_HIGH;
                }
                if(StringUtils.isNotBlank(content)) {
                    TWarnRecords warnRecord = new TWarnRecords();
                    warnRecord.setWarnContent(content);
                    warnRecord.setWarnType(warnType);
                    warnRecord.setWarnValue(null == heartRate ?"0": String.valueOf(heartRate));
                    warnRecords.add(warnRecord);
                }
            }

            // 收缩压预警
            if(WarnConstants.WARN_TYPE_TJ03_SBP.equals(warnType)){
                Integer sbp = data.getSbp();
                String content = "";
                if(null != sbp && sbp != 0 && sbp < e.getLowerLimit()){
                    content = WarnConstants.WARN_CONTENT_SBP_LOW;
                }
                if(null != sbp && sbp != 0 && sbp > e.getUpperLimit()){
                    content = WarnConstants.WARN_CONTENT_SBP_HIGH;
                }
                if(StringUtils.isNotBlank(content)) {
                    TWarnRecords warnRecord = new TWarnRecords();
                    warnRecord.setWarnContent(content);
                    warnRecord.setWarnType(warnType);
                    warnRecord.setWarnValue(null == sbp ?"0": String.valueOf(sbp));
                    warnRecords.add(warnRecord);
                }
            }

            // 收缩压预警
            if(WarnConstants.WARN_TYPE_TJ03_DBP.equals(warnType)){
                Integer dbp = data.getDbp();
                String content = "";
                if(null != dbp && dbp != 0 && dbp < e.getLowerLimit()){
                    content = WarnConstants.WARN_CONTENT_DBP_LOW;
                }
                if(null != dbp && dbp != 0 && dbp > e.getUpperLimit()){
                    content = WarnConstants.WARN_CONTENT_DBP_HIGH;
                }
                if(StringUtils.isNotBlank(content)) {
                    TWarnRecords warnRecord = new TWarnRecords();
                    warnRecord.setWarnContent(content);
                    warnRecord.setWarnType(warnType);
                    warnRecord.setWarnValue(null == dbp ?"0": String.valueOf(dbp));
                    warnRecords.add(warnRecord);
                }
            }
        });

        // 如果预警信息不为空
        if(! warnRecords.isEmpty()){
            for (TWarnRecords warn : warnRecords) {
                warn.setHospitalId(record.getHospitalId());
                warn.setDeptId(record.getDeptId());
                warn.setVisitNo(record.getVisitNo());
                warn.setEquipmentNo(data.getEquipmentNo());
                warn.setCreateTime(data.getCreateTime());
                warn.setHasHandle(WarnConstants.WARN_HANDLE_UNPROCESSED);
                warn.setNextReminderTime(new Date());
            }

            if(!recordsService.saveOrUpdateRecord(warnRecords)){
                log.error("异常记录保存或更新失败!设备号：{}，监测时间：{}", data.getEquipmentNo(), data.getCreateTime());
            }
        }

    }

    private TJ03Data getRecordFromDto(TJ03DataDto tj03DataDto){
        TJ03Data record = new TJ03Data();
        record.setProductId(tj03DataDto.getProductKey());
        record.setEquipmentNo(tj03DataDto.getDeviceName());

        if(tj03DataDto.getItems().getBatpt() != null){
            record.setBatpt(Integer.parseInt(tj03DataDto.getItems().getBatpt().getValue()));
            record.setCreateTime(tj03DataDto.getItems().getBatpt().getTime());
        }
        if(tj03DataDto.getItems().getWState() != null){
            record.setWState(tj03DataDto.getItems().getWState().getValue());
            record.setCreateTime(tj03DataDto.getItems().getWState().getTime());
        }
        if(tj03DataDto.getItems().getFailState() != null){
            record.setRestHeart(tj03DataDto.getItems().getFailState().getValue());
            record.setCreateTime(tj03DataDto.getItems().getFailState().getTime());
        }
        if(tj03DataDto.getItems().getBPTRslt() != null){
            record.setBptResult(tj03DataDto.getItems().getBPTRslt().getValue());
            record.setCreateTime(tj03DataDto.getItems().getBPTRslt().getTime());
        }
        if(tj03DataDto.getItems().getBPTS() != null){
            record.setBptStatus(tj03DataDto.getItems().getBPTS().getValue());
            record.setCreateTime(tj03DataDto.getItems().getBPTS().getTime());
        }
        if(tj03DataDto.getItems().getPValue() != null){
            record.setPValue(Long.parseLong(tj03DataDto.getItems().getPValue().getValue()));
            record.setCreateTime(tj03DataDto.getItems().getPValue().getTime());
        }
        if(tj03DataDto.getItems().getBPSy() != null){
            record.setSbp(Integer.parseInt(tj03DataDto.getItems().getBPSy().getValue()));
            record.setCreateTime(tj03DataDto.getItems().getBPSy().getTime());
        }
        if(tj03DataDto.getItems().getBPDi() != null){
            record.setDbp(Integer.parseInt(tj03DataDto.getItems().getBPDi().getValue()));
            record.setCreateTime(tj03DataDto.getItems().getBPDi().getTime());
        }
        if(tj03DataDto.getItems().getBPTTRslt() != null){
            record.setBpttResult(tj03DataDto.getItems().getBPTTRslt().getValue());
            record.setCreateTime(tj03DataDto.getItems().getBPTTRslt().getTime());
        }
        if(tj03DataDto.getItems().getBPTTS() != null){
            record.setBpttStatus(tj03DataDto.getItems().getBPTTS().getValue());
            record.setCreateTime(tj03DataDto.getItems().getBPTTS().getTime());
        }
        if(tj03DataDto.getItems().getInflDur() != null){
            record.setInflDur(Long.parseLong(tj03DataDto.getItems().getInflDur().getValue()));
            record.setCreateTime(tj03DataDto.getItems().getInflDur().getTime());
        }
        if(tj03DataDto.getItems().getEcgDat() != null){
            record.setEcgData(tj03DataDto.getItems().getEcgDat().getValue());
            record.setCreateTime(tj03DataDto.getItems().getEcgDat().getTime());
        }
        if(tj03DataDto.getItems().getEcgPatchStatus() != null){
            record.setEcgPatchStatus(tj03DataDto.getItems().getEcgPatchStatus().getValue());
            record.setCreateTime(tj03DataDto.getItems().getEcgPatchStatus().getTime());
        }
        if(tj03DataDto.getItems().getEcgSeq() != null){
            record.setEcgSeq(tj03DataDto.getItems().getEcgSeq().getValue());
            record.setCreateTime(tj03DataDto.getItems().getEcgSeq().getTime());
        }
        if(tj03DataDto.getItems().getEcgPatchPlginSta() != null){
            record.setEcgPatchPlginStatus(tj03DataDto.getItems().getEcgPatchPlginSta().getValue());
            record.setCreateTime(tj03DataDto.getItems().getEcgPatchPlginSta().getTime());
        }
        if(tj03DataDto.getItems().getPowerStatus() != null){
            record.setPowerStatus(tj03DataDto.getItems().getPowerStatus().getValue());
            record.setCreateTime(tj03DataDto.getItems().getPowerStatus().getTime());
        }

        return record;
    }

    @Override
    public List<APITJ03HrData> listHrData(String equipmentNo, Date startTime, Date endTime) {
        return j03DataHrMapper.listData(equipmentNo, startTime.getTime(), endTime.getTime());
    }

    @Override
    public List<APITJ03BpData> listBpData(String equipmentNo, Date startTime, Date endTime) {
        return j03DataMapper.bpDataList(equipmentNo, startTime, endTime);
    }

    @Override
    public List<APITJ03EcgData> listECGData(String equipmentNo, Date startTime, Date endTime) {
        return j03DataEcgMapper.ecgDataList(equipmentNo, startTime.getTime(), endTime.getTime());
    }

    @Override
    public APITJ03HrData latestHrData(String equipmentNo, Date startTime, Date endTime) {
        return j03DataHrMapper.latestData(equipmentNo, startTime.getTime(), endTime.getTime());
    }

    @Override
    public int sendCommand(String equipmentNo, RunSetParam runSet) {
        String set = JSON.toJSONString(runSet);
        System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
        System.out.println();
        System.out.println();
        System.out.println("向设备号："+ equipmentNo +"发送数据：");
        System.out.println(set);

        DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", amqp.getAccessKey(), amqp.getAccessSecret());
        IAcsClient client = new DefaultAcsClient(profile);
        String productKey = "gni44gY5Frc";

        PubRequest request = new PubRequest();
        request.setIotInstanceId(amqp.getIotInstanceId());
        request.setProductKey(productKey);
        request.setTopicFullName("/"+productKey+"/"+equipmentNo+"/user/update");
        request.setMessageContent(StringUtils.stringToBase64(set));

        try {
            PubResponse response = client.getAcsResponse(request);
            System.out.println("发送结果：" + new Gson().toJson(response));
            return 1;
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
        System.out.println();
        System.out.println();
        System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
        return 0;
    }

    @Override
    public APITJ03RealTimeData getTj03RealTimeData(List<RecordsReq> reqs) {
        APITJ03RealTimeData data = new APITJ03RealTimeData();
        for (RecordsReq req : reqs) {
            String equipmentNo = req.getEquipmentNo();
            Date startTime = req.getStartTime();
            Date endTime = req.getEndTime();

            TJ03Data equipmentTJ03MonitorRecords = j03DataMapper.selectLastRecord(equipmentNo, startTime, endTime);
            if(equipmentTJ03MonitorRecords != null) {
                Date recordTime = equipmentTJ03MonitorRecords.getCreateTime();
                BeanUtils.copyBeanProp(data, equipmentTJ03MonitorRecords);
                data.setBpTime(recordTime);
                data.setBpttTime(recordTime);
                break ;
            } else {
                reqs.remove(req);
            }
        }

        // 查询穿戴状态
        if(data.getWState() == null && !reqs.isEmpty()) {
            for (RecordsReq req : reqs) {
                TJ03Data wStateRecord = j03DataMapper.selectLastWStateDataIsNotNullRecord(req.getEquipmentNo(), req.getStartTime(), req.getEndTime());
                if(wStateRecord != null) {
                    data.setWState(wStateRecord.getWState());
                    break ;
                }
            }
        }

        // 查询故障状态
        if(data.getRestHeart() == null && !reqs.isEmpty()) {
            for (RecordsReq req : reqs) {
                TJ03Data restHeartRecord = j03DataMapper.selectLastRestHeartDataIsNotNullRecord(req.getEquipmentNo(), req.getStartTime(), req.getEndTime());
                if(restHeartRecord != null) {
                    data.setRestHeart(restHeartRecord.getRestHeart());
                    break ;
                }
            }
        }

        // 查询血压不为空的数据
        if((data.getSbp() == null || data.getDbp() == null) && !reqs.isEmpty()) {
            for (RecordsReq req : reqs) {
                TJ03Data bpDataIsNotNull = j03DataMapper.selectLastBPDataIsNotNullRecord(req.getEquipmentNo(), req.getStartTime(), req.getEndTime());
                if(bpDataIsNotNull != null) {
                    data.setSbp(bpDataIsNotNull.getSbp());
                    data.setDbp(bpDataIsNotNull.getDbp());
                    data.setPValue(bpDataIsNotNull.getPValue());
                    data.setBptStatus(bpDataIsNotNull.getBptStatus());
                    data.setBptResult(bpDataIsNotNull.getBptResult());
                    data.setBpTime(bpDataIsNotNull.getCreateTime());
                    break ;
                }
            }
        }

//        // 查询气密性相关参数不为空的数据
//        if((data.getBpttStatus() == null || data.getBpttResult() == null) && !reqs.isEmpty()) {
//            for (RecordsReq req : reqs) {
//                TJ03Data bpttDataIsNotNull = j03DataMapper.selectLastBPTTDataIsNotNullRecord(req.getEquipmentNo(), req.getStartTime(), req.getEndTime());
//                if (bpttDataIsNotNull != null) {
//                    data.setBpttStatus(bpttDataIsNotNull.getBpttStatus());
//                    data.setBpttResult(bpttDataIsNotNull.getBpttResult());
//                    data.setInflDur(bpttDataIsNotNull.getInflDur());
//                    data.setBpttTime(bpttDataIsNotNull.getCreateTime());
//                    break;
//                }
//            }
//        }

        // 查询心电贴状态
        if(data.getEcgPatchStatus() == null && !reqs.isEmpty()) {
            for (RecordsReq req : reqs) {
                TJ03Data ecgPatchRecord = j03DataMapper.selectLastEcgPatchStatusDataIsNotNullRecord(req.getEquipmentNo(), req.getStartTime(), req.getEndTime());
                if(ecgPatchRecord != null) {
                    data.setEcgPatchStatus(ecgPatchRecord.getEcgPatchStatus());
                    break;
                }
            }
        }
        if(data.getEcgPatchPlginStatus() == null && !reqs.isEmpty()) {
            for (RecordsReq req : reqs) {
                TJ03Data ecgPatchPlginStatusRecords = j03DataMapper.selectLastEcgPatchPlginStatusDataIsNotNullRecord(req.getEquipmentNo(), req.getStartTime(), req.getEndTime());
                if(ecgPatchPlginStatusRecords != null) {
                    data.setEcgPatchPlginStatus(ecgPatchPlginStatusRecords.getEcgPatchPlginStatus());
                    data.setEcgSeq(ecgPatchPlginStatusRecords.getEcgSeq());
                    break;
                }
            }
        }

        // 查询最新的心率
        for (RecordsReq req : reqs) {
            TJ03DataHr recordsHr = j03DataHrMapper.selectLastHrDataByEquipment(req.getEquipmentNo(), req.getStartTime().getTime(), req.getEndTime().getTime());
            if (recordsHr != null) {
                data.setHr(recordsHr.getHr() == null ? 0 : recordsHr.getHr());
                data.setHrTime(new Date(recordsHr.getCreateTime()));
                break;
            }
        }

        // 开关机状态
        if(data.getCreateTime() == null || (System.currentTimeMillis() - data.getCreateTime().getTime()) >  10 * 60 * 1000) {
            data.setPowerStatus("1");
        } else {
            data.setPowerStatus("0");
        }

        return data;
    }

    @Override
    public APITJ03RealTimeData getLatestBatteryData(String equipmentNo) {
        APITJ03RealTimeData apitj03RealTimeData = new APITJ03RealTimeData();
        TJ03Data tj03Data = j03DataMapper.selectLastRecord(equipmentNo, null, null);
        if (tj03Data != null) {
            apitj03RealTimeData.setBatpt(tj03Data.getBatpt());
            apitj03RealTimeData.setCreateTime(tj03Data.getCreateTime());
            apitj03RealTimeData.setEquipmentNo(tj03Data.getEquipmentNo());
            return apitj03RealTimeData;
        }
        return apitj03RealTimeData;
    }

    @Override
    public APITJ03RealTimeData getLatestData(String equipmentNo) {
        APITJ03RealTimeData data = new APITJ03RealTimeData();
        TJ03Data equipmentTJ03MonitorRecords = j03DataMapper.selectLastRecord(equipmentNo, null, null);
        if(equipmentTJ03MonitorRecords != null) {
            Date recordTime = equipmentTJ03MonitorRecords.getCreateTime();
            BeanUtils.copyBeanProp(data, equipmentTJ03MonitorRecords);
            data.setBpTime(recordTime);
            data.setBpttTime(recordTime);

            // 查询穿戴状态
            if(data.getWState() == null) {
                TJ03Data wStateRecord = j03DataMapper.selectLastWStateDataIsNotNullRecord(equipmentNo, null, null);
                if(wStateRecord != null) {
                    data.setWState(wStateRecord.getWState());
                }
            }

            // 查询故障状态
            if(data.getRestHeart() == null) {
                TJ03Data restHeartRecord = j03DataMapper.selectLastRestHeartDataIsNotNullRecord(equipmentNo, null, null);
                if(restHeartRecord != null) {
                    data.setRestHeart(restHeartRecord.getRestHeart());
                }
            }
            // 查询血压不为空的数据
            if(data.getSbp() == null || data.getDbp() == null) {
                data.setBpTime(null);
                TJ03Data bpDataIsNotNull = j03DataMapper.selectLastBPDataIsNotNullRecord(equipmentNo, null, null);
                if(bpDataIsNotNull != null) {
                    data.setSbp(bpDataIsNotNull.getSbp());
                    data.setDbp(bpDataIsNotNull.getDbp());
                    data.setPValue(bpDataIsNotNull.getPValue());
                    data.setBptStatus(bpDataIsNotNull.getBptStatus());
                    data.setBptResult(bpDataIsNotNull.getBptResult());
                    data.setBpTime(bpDataIsNotNull.getCreateTime());
                }
            }
            // 查询气密性相关参数不为空的数据
            if(data.getBpttStatus() == null || data.getBpttResult() == null) {
                data.setBpttTime(null);
                TJ03Data bpttDataIsNotNull = j03DataMapper.selectLastBPTTDataIsNotNullRecord(equipmentNo, null, null);
                if (bpttDataIsNotNull != null) {
                    data.setBpttStatus(bpttDataIsNotNull.getBpttStatus());
                    data.setBpttResult(bpttDataIsNotNull.getBpttResult());
                    data.setInflDur(bpttDataIsNotNull.getInflDur());
                    data.setBpttTime(bpttDataIsNotNull.getCreateTime());
                }
            }
        }
        return data;
    }
}
